<template>
  <view>
    <nav-bar title="会员中心"></nav-bar>
    <scroll-view scroll-y :style="{ height: mainScrollHeight }">
      <view class="bg-box"></view>
      <view class="card-box">
        <view class="card-item custom-vip-card" 
        :style="{
          background:`url(${baseImgUrl}/userImg/img_customization.png) no-repeat`,
          backgroundSize: 'cover'
          }"
        @click="clickCardItem(2)">
          <view class="mark-box" v-if="activeCard === 1"></view>
          <view class="card-title">
            <image
              class="custom-img"
              :src="baseIconUrl + '/userIcon/icon_badge.png'"
            />
            <text style="margin-left: 13rpx;">VIP定制会员</text>
            <image
              class="preferential-img"
              :src="baseIconUrl + '/userIcon/icon_preferential.png'"
            />
          </view>
          <view class="card-desc">开通定制会员即可享受定制服务</view>
          <view v-if="activeCard === 2" class="choose-icon">
            <uni-icons type="checkbox" color="#682604"></uni-icons>
          </view>
        </view>
        <view class="card-item vip-card" @click="clickCardItem(1)">
          <view class="mark-box" v-if="activeCard === 2"></view>
          <view class="card-title">
            普通会员
            <image
              class="preferential-img"
              :src="baseIconUrl + '/userIcon/icon_preferential.png'"
            />
          </view>
          <view class="card-desc">
            {{ memberUser ? '会员将于' + memberDate + '到期' : '开通正式会员即可享受更多会员权益' }}
          </view>
          <view v-if="activeCard === 1" class="choose-icon">
            <uni-icons type="checkbox" color="#682604"></uni-icons>
          </view>
        </view>
      </view>
      <view class="custom-list" v-if="activeCard === 2">
        <view class="member-title">
          VIP定制专享权益
        </view>
        <view class="member-list">
          <view class="member-item" v-for="(item, index) in customOperateList" :key="index">
            <view class="icon">
              <image
                class="icon-img"
                :src="`${baseIconUrl}/userIcon/${item.icon}`"
              />
            </view>
            <view class="label">{{ item.label }}</view>
            <view class="desc">{{ item.desc }}</view>
          </view>
        </view>
        <view v-if="isLoading" class="common-loading">
          <image class="loading-img" :src="baseIconUrl + '/commonIcon/icon_loading.png'" />
          正在加载数据，请稍后......
        </view>
        <view class="common-no-data" v-else-if="!customVipList || customVipList.length === 0">
          <image class="no-data-img" :src="baseIconUrl + '/commonIcon/icon_no_data.png'" />
          <view class="text">暂无数据~</view>
        </view>
        <view v-else>
          <view
            class="custom-item"
            v-for="(item, index) in customVipList"
            :key="index"
            @click="clickCustomItem(item)"
          >
            <view class="choose-icon" @click.stop="clickChooseIcon(item)">
              <uni-icons
                v-if="chooseCustom.id === item.id"
                type="checkbox-filled"
                color="#2A82E4"
                size="28"
              ></uni-icons>
              <uni-icons
                v-else
                type="circle"
                color="#2A82E4"
                size="28"
              ></uni-icons>
            </view>
            <view class="img-box">
              <image
                class="serve-img"
                :src="item.img || baseImgUrl + '/userImg/img_service_small_bg.png'"
                mode="aspectFill"
              />
            </view>
            <view class="content-box">
              <view class="name ellipsis-text">{{ item.name }}</view>
              <view class="validity-period">有效期：{{ item.validMonths }}个月</view>
              <view class="price">￥{{ item.price }}</view>
            </view>
          </view>
        </view>
      </view>
      <view class="member-box" v-else>
        <view class="member-title">
          会员专享权益
        </view>
        <view class="member-list">
          <view class="member-item" v-for="(item, index) in memberList" :key="index">
            <view class="icon">
              <image
                class="icon-img"
                :src="`${baseIconUrl}/userIcon/${item.icon}`"
              />
            </view>
            <view class="label">{{ item.label }}</view>
            <view class="desc">{{ item.desc }}</view>
          </view>
        </view>
        <view class="service-detail">
          <view class="service-title">
            <view class="line"></view>
            <view class="word">服务详情</view>
          </view>
          <view class="service-content">
            <rich-text class="user-content" :nodes="memberData.serviceDetail || '暂无'"></rich-text>
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="bottom-confirm-box" v-if="(!memberUser && activeCard === 1) || activeCard === 2">
      <view class="btn-box" :style="{ background: `url(${baseImgUrl}/userImg/img_bottom_btn_bg.png) no-repeat`, backgroundSize: '100% auto' }">
        <view class="price-box">
          <view class="price" v-if="activeCard === 2">
            {{ chooseCustom.price || '' }}
          </view>
          <view class="price" v-else>{{ memberData.price }}</view>
          <view class="unit" v-if="activeCard === 2">
            <view v-if="chooseCustom.id">元/{{ chooseCustom.validMonths || 0 }}个月</view>
          </view>
          <view class="unit" v-else>/年</view>
        </view>
        <view class="btn" @click="clickConfirmBuy">确认开通</view>
      </view>
      <view class="read-text">
        <uni-icons
          v-if="!isReadService[activeCard]"
          type="circle"
          :size="20"
          color="#999999"
          class="icon"
          @click="isReadService[activeCard] = true"
        ></uni-icons>
        <uni-icons
          v-else
          type="checkbox-filled"
          :size="20"
          color="#115BAA"
          class="icon"
          @click="isReadService[activeCard] = false"
        ></uni-icons>
        <view>开通前请阅读<text class="text" @click="clickViewService">《{{ serviceName }}》</text></view>
      </view>
    </view>
    <you-popup
      dialogWidth="90vw"
      :popupVisible="servicePopup"
      :popupTitle="serviceName"
      :showBtn="false"
	    @popupClose="servicePopup = false"
    >
      <template #popupContent>
        <view class="dialog-content">
          <scroll-view scroll-y class="service-box">
            <view class="service-content">
              <rich-text class="user-content" :nodes="serviceContent"></rich-text>
            </view>
          </scroll-view>
          <view class="close-btn" @click="clickAlView">确定</view>
        </view>
      </template>
    </you-popup>
  </view>
</template>

<script>
  import api_user from '@/api/user'
  import api_common from '@/api/common'
  import api_login from '@/api/login'
  import { baseImgUrl, baseIconUrl } from '@/config'
  export default {
    name: 'ActivateMember',
    data() {
      return {
        baseImgUrl,
        baseIconUrl,
        activeCard: 1, // 1 普通vip 2 定制vip 
        mainScrollHeight: 0,
        isLoading: false,
        customVipList: [],
        chooseCustom: {},
        customOperateList: [
          { label: '专业评估', desc: '一年四次', icon: 'icon_member_view.png' },
          { label: '课程跟练', desc: '专业指导', icon: 'icon_member_discount.png' },
          { label: '生日礼包', desc: '惊喜好礼', icon: 'icon_member_cake.png' },
          { label: '专属客服', desc: '1V1服务', icon: 'icon_member_customer.png' },
          { label: '专家问诊', desc: '线下预约', icon: 'icon_member_ask.png' },
          { label: '会员定制', desc: '专属训练方案', icon: 'icon_member_vip.png' }
        ],
        memberUser: false,
        memberDate: '',
        memberData: {},
        memberList: [
          { label: '专业评估', desc: '一年四次', icon: 'icon_member_view.png' },
          { label: '课程跟练', desc: '专业指导', icon: 'icon_member_discount.png' },
          { label: '生日礼包', desc: '惊喜好礼', icon: 'icon_member_cake.png' }
        ],
        serviceName: '普通会员服务协议',
        isReadService: {
          1: false,
          2: false
        },
        servicePopup: false,
        serviceContent: ''
      }
    },
    onLoad(options) {
      this.getElementHeight()
      if (options.activeCard) {
        this.activeCard = Number(options.activeCard)
        this.serviceName = this.activeCard === 1 ? '普通会员服务协议' : 'VIP定制会员服务协议'
      }
      const userInfo = uni.getStorageSync('allUserInfo')
      if (userInfo.isMember === 2 && this.activeCard === 1) {
        this.memberUser = true
        this.getCardDate()
      }
      this.getCustomList()
    },
    methods: {
      getElementHeight() {
        setTimeout(() => {
          // 创建查询对象
          const query = uni.createSelectorQuery().in(this)
          // 选择我们想要的元素
          query.select('.bottom-confirm-box').boundingClientRect(data => {
            // data是一个包含元素尺寸信息的对象
            const pageHeightConfig = this.$store.getters.heightData
            if (data) {
              // 获取元素高度
              const height = data.height
              this.mainScrollHeight = pageHeightConfig.noTabMainHeight - height + pageHeightConfig.safeHeight + 'px'
            } else {
              this.mainScrollHeight = pageHeightConfig.noTabMainHeight + 'px'
            }
          }).exec()
        }, 200)
      },
      getCardDate() {
        const params = {
          cardType: 1, // 1  普通会员  2  vip定制
        }
        api_user.fetchCardRecordList(params).then(res => {
          if (res.code !== 200) return
          this.memberDate = res.rows && res.rows.length ? res.rows[0].expirationTime || '' : ''
        })
      },
      getCustomList() {
        this.isLoading = true
        const params = {
          pageNum: 1,
          pageSize: 1000,
          cardType: this.activeCard
        }
        api_user.fetchCardList(params).then(res => {
          if (res.code !== 200) return
          if (this.activeCard === 1) {
            const result = res.rows[0]
            result.serviceDetail = result.serviceDetail && result.serviceDetail.replace(/\n/g, '<br/>')
            this.memberData = result
          } else {
            this.customVipList.push(...res.rows)
          }
          this.isLoading = false
        })
      },
      async clickCardItem(value) {
        await this.getElementHeight()
        this.activeCard = value
        this.serviceName = value === 1 ? '普通会员服务协议' : 'VIP定制会员服务协议'
        if (value === 2) {
          this.pageNum = 1
          this.customVipList = []
        }
        this.getCustomList()
      },
      clickCustomItem(item) {
        uni.navigateTo({
          url: `/subPages/userIndex/memberCenter/customServeDetail?id=${item.id}`
        })
      },
      clickChooseIcon(item) {
        if (this.chooseCustom.id === item.id) {
          this.chooseCustom = {}
        } else {
          this.chooseCustom = item
        }
      },
      clickViewService() {
        const params = {
          id: this.activeCard === 1 ? 11 : 12
        }
        api_user.fetchNewsDetail(params).then(res => {
          if (res.code !== 200) return
          this.serviceContent = res.data.content && res.data.content.replace(/\n/g, '<br/>')
          this.servicePopup = true
        })
      },
      clickAlView() {
        this.isReadService[this.activeCard] = true
        this.servicePopup = false
      },
      clickConfirmBuy() {
        if (!this.isReadService[this.activeCard]) return uni.showToast({
          title: '请选阅读《' + this.serviceName + '》',
          icon: 'none',
          mask: true
        })
        const price = this.activeCard === 1 ? this.memberData.price : this.chooseCustom.price
        const cardId = this.activeCard === 1 ? this.memberData.id : null
        if (!price || price <= 0) return uni.showToast({
          title: '请选择要购买的服务',
          icon: 'none',
          mask: true
        })
        const params = {
          price,
          totalNum: 1,
          goodId: this.activeCard === 1 ? this.memberData.id : this.chooseCustom.id,
          orderType: this.activeCard // 1 普通会员  2 vip定服务  3 康复辅具
        }
        api_common.fetchPayParams(params).then(res => {
          if (res.code !== 200) return
          const resParams = {
            timeStamp: res.data.data.timestamp,
            nonceStr: res.data.data.nonceStr,
            package: res.data.data.package,
            signType: res.data.data.signType,
            paySign: res.data.data.paySign
          }
          let that = this
          // 调用微信小程序的支付接口
          uni.requestPayment({
            ...resParams,
            success(successRes) {
              // 支付成功的回调
              uni.showToast({
                title: '支付成功！',
                icon: 'success',
                mask: true
              })
              api_login.fetchUserInfo().then(infoRes => {
                if (infoRes.code !== 200) return
                const userInfo = {
                  baUserId: infoRes.baUser.id,
                  ...infoRes.baUser
                }
                uni.setStorageSync('allUserInfo', userInfo)
                if (that.activeCard === 2) {
                  uni.redirectTo({
                    url: `/subPages/userIndex/memberCenter/basicInfo?cardId=${cardId}&orderNum=${res.data.data.orderNum}`
                  })
                } else {
                  if (userInfo.isMember === 2) {
                    that.memberUser = true
                    that.getCardDate()
                  } else {
                    that.getCustomList()
                  }
                }
              })
            },
            fail(error) {
              // 支付失败的回调
              uni.showToast({
                title: '支付失败',
                icon: 'none',
                duration: 2000
              })
            }
          })
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .bg-box {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 822rpx;
    background-color: #1C172B;
    z-index: -1;
  }
  .card-box {
    padding: 20px 30rpx;
    .card-item {
      position: relative;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 100px;
      padding: 40rpx 40rpx 28rpx;
      border-radius: 32rpx;
      .mark-box {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 32rpx;
        background-color: rgba(0, 0, 0, .2);
      }
      .card-title {
        display: flex;
        align-items: center;
        font-size: 40rpx;
        font-weight: 700;
        color: #682604;
      }
      .card-desc {
        font-size: 24rpx;
        color: #682604;
      }
      .choose-icon {
        position: absolute;
        top: 70rpx;
        right: 20rpx;
      }
      .custom-img{
        width: 35rpx;
        height: 40rpx;
      }
      .preferential-img{
        width: 140rpx;
        height: 48rpx;
        position: absolute;
        top: 0;
        right: 0;
      }
    }
    .vip-card {
      margin-top: 10px;
      background: linear-gradient(129.98deg, #FFEBC4 0%, #F1CD8E 100%);
    }
  }
  .custom-list {
    padding: 60rpx 30rpx 10rpx;
    border-radius: 32rpx 32rpx 0 0;
    background-color: #FFF;
    .custom-item {
      display: flex;
      align-items: center;
      margin: 32rpx 0;
      .choose-icon {
        margin-right: 24rpx;
      }
      .img-box {
        width: 270rpx;
        height: 180rpx;
        margin-right: 20rpx;
        border-radius: 16rpx;
        .serve-img {
          width: 100%;
          height: 100%;
        }
      }
      .content-box {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .name {
          font-size: 32rpx;
          font-weight: 500;
          color: #333;
        }
        .validity-period {
          margin: 40rpx 0;
          font-size: 24rpx;
          color: #999;
        }
        .price {
          text-align: right;
          font-size: 42rpx;
          font-weight: 500;
          color: #FF513A;
        }
      }
    }
  }
  .member-title {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 40rpx;
    font-weight: 500;
    margin-bottom: 64rpx;
  }
  .member-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    .member-item {
      width: 33.33%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-bottom: 62rpx;
      .icon {
        width: 90rpx;
        height: 90rpx;
        border-radius: 45rpx;
        .icon-img {
          width: 100%;
          height: 100%;
        }
      }
      .label {
        margin: 16rpx 0;
        font-size: 26rpx;
        color: 3333;
      }
      .desc {
        font-size: 26rpx;
        color: #999;
      }
    }
  }
  .member-box {
    padding: 60rpx 100rpx;
    border-radius: 32rpx 32rpx 0 0;
    background-color: #FFF;    
    .service-detail {
      .service-title {
        display: flex;
        align-items: center;
        .line {
          width: 8rpx;
          height: 30rpx;
          background:#115baa;
          border-radius:4rpx;
        }
        .word {
          font-size: 28rpx;
          color: #333;
          margin-left: 20rpx;
        }
      }
      .service-content {
        font-size: 28rpx;
        color: #666;
        line-height: 42rpx;
        margin-top: 10rpx;
      }
    }
  }
  .bottom-confirm-box {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 28rpx 30rpx env(safe-area-inset-bottom);
    box-shadow: 0rpx 0rpx 16rpx  rgba(0, 0, 0, .2);
    background-color: #FFF;
    .btn-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 90rpx;
      margin-bottom: 22rpx;
      padding: 0 52rpx 0 40rpx;
      background-size: 100% auto;
      .price-box {
        display: flex;
        align-items: center;
        .price {
          margin-right: 10rpx;
          font-size: 48rpx;
          font-weight: 700;
          color: #F0CB91;
        }
        .unit {
          font-size: 28rpx;
          font-weight: 400;
          color: #F0CB91;
        }
      }
      .btn {
        font-size: 32rpx;
        font-weight: 500;
        color: #682604;
      }
    }
    .read-text {
      display: flex;
      align-items: center;
      padding: 0 10rpx;
      font-size: 28rpx;
      color: #333;
      .text {
        color: #682604;
      }
    }
  }
  .dialog-content {
    padding-bottom: 36rpx;
    .service-box {
      max-height: 55vh;
      .service-content {
        padding: 30rpx 40rpx;
        .text {
          width: 100%;
        }
      }
    }
    .close-btn {
      width: 80%;
      height: 70rpx;
      margin: 40rpx auto 0;
      border-radius: 35rpx;
      text-align: center;
      font-size: 32rpx;
      font-family: PingFang SC;
      font-weight: 500;
      line-height: 70rpx;
      color: #FFFFFF;
      background: #115BAA;
    }
  }
</style>
